// src/router/index.js
import { ElMessage } from "element-plus";
import { createRouter, createWebHistory } from "vue-router";
import { useUserStore } from "@/stores/model/user";

const main = () => import("@/views/Main.vue");

const routes = [
  {
    path: "/login",
    name: "login",
    meta: { title: "登录", name: "login" },
    component: () => import("@/views/Login.vue"),
  },
  {
    path: "/",
    name: "main",
    redirect: "/generalIndex",
    component: main,
    meta: { title: "通用首页", name: "main", requiresAuth: true },
    children: [
      {
        path: "generalIndex",
        name: "generalIndex",
        meta: { title: "通用首页", name: "home", requiresAuth: true },
        component: () => import("@/views/index.vue"),
      },
      {
        path: "personalData",
        name: "personalData",
        meta: { title: "个人中心", name: "personalData", requiresAuth: true },
        component: () => import("@/views/personalData.vue"),
      },
    ],
  },

  {
    path: "/404",
    name: "404",
    meta: { title: "404", name: "404" },
    component: () => import("@/views/404.vue"),
  },

  // {
  //   path: "/settingSystem",
  //   name: "settingSystem",
  //   redirect: "/settingSystem/settingRouter",
  //   component: main,
  //   meta: { title: "系统设置", name: "settingSystem", requiresAuth: true },
  //   children: [
  //     {
  //       path: "settingRouter",
  //       name: "router",
  //       meta: {
  //         title: "设置路由",
  //         name: "settingRouter",
  //         requiresAuth: true,
  //       },
  //       component: () => import("@/views/admin/SettingRouter.vue"),
  //     },
  //     {
  //       path: "settingUser",
  //       name: "user",
  //       meta: {
  //         title: "用户管理",
  //         name: "settingUser",
  //         requiresAuth: true,
  //       },
  //       component: () => import("@/views/admin/SettingUser.vue"),
  //     },
  //     {
  //       path: "settingRole",
  //       name: "role",
  //       meta: {
  //         title: "角色管理",
  //         name: "settingRole",
  //         requiresAuth: true,
  //       },
  //       component: () => import("@/views/admin/SettingRole/index.vue"),
  //     },
  //   ],
  // },

  // 重定向
  // { path: "/:pathMatch(.*)*", redirect: "/login" },
];

const dynamicRoutes = [];

const router = createRouter({
  history: createWebHistory(),
  routes,
});

function addDynamicRoutes(routes) {
  routes.forEach((route) => {
    if (route.menuType == "2") {
      router.addRoute("main", route);
      dynamicRoutes.push(route);
    } else {
      router.addRoute(route);
      dynamicRoutes.push(route);
    }
  });

  router.addRoute({
    path: "/:pathMatch(.*)*",
    name: "__redirect",
    redirect: "/404",
  });
}

function resetRoutes() {
  dynamicRoutes.forEach((route) => {
    router.removeRoute(route.name);
  });

  router.removeRoute("__redirect");
  dynamicRoutes.length = 0; // 清空动态路由数组
}

router.beforeEach(async (to, from, next) => {
  const token = localStorage.getItem("token");
  const userStore = useUserStore();

  if (to.matched.some((record) => record.meta.requiresAuth)) {
    if (!token) {
      console.log("未登录,无token");
      ElMessage.error({
        message: "请先登录",
      });
      return next({ name: "login" });
    }
  }

  if (to.path === "/login") {
    resetRoutes();
    return next();
  }

  if (dynamicRoutes.length === 0) {
    const dynamicRoutesData = await userStore.getUserMenuTree();
    addDynamicRoutes(dynamicRoutesData);
    //处理没有任何路由的角色菜单---注意：没有目录的路由，重定向出现问题
    if (dynamicRoutesData.length === 0) {
      router.addRoute({
        path: "/:pathMatch(.*)*",
        name: "__redirect",
        redirect: "/404",
      });
      return next();
    }

    return next({ ...to, replace: true });
  }

  next();
});

export default router;
